﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace cs_utilities.win32
{
    public class safe_native_handle
    {
        private IntPtr ptr_ = IntPtr.Zero;
        public IntPtr NativePointer
        {
            get { return ptr_; }
        }

        //---------------------------------------------------------------------------
        public safe_native_handle(IntPtr handle)
        {
            ptr_ = handle;
        }
        //---------------------------------------------------------------------------
        ~safe_native_handle()
        {
            if (ptr_ != IntPtr.Zero)
            {
                if (!win32.CloseHandle(ptr_))
                {
                    string msg = string.Format("Failed to close native handle. Error: 0x{0}", Marshal.GetLastWin32Error().ToString("x"));
                    throw new Exception(msg);
                }
            }
        }
        //---------------------------------------------------------------------------
    }
}